package com.learn.english.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.learn.english.constants.CacheConstants;
import com.learn.english.enums.TimeEnum;
import com.learn.english.mapper.CourseMapper;
import com.learn.english.model.entity.Course;
import com.learn.english.model.ro.CourseRo;
import com.learn.english.service.ICourseService;
import com.learn.english.service.RedisService;
import jakarta.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
//总共设计
//首屏顶部显示内容:轮播图，/top_banner/1接口获取数据
//次屏显示推荐课程，每行5张卡片，总共三行
/**
 * @author TISNIW
 * @version 1.0
 * @desc
 */
@Service
public class CourseServiceImpl implements ICourseService {

    private static final Logger log = LoggerFactory.getLogger(CourseServiceImpl.class);
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public List<CourseRo> page(Integer pageNum, Integer pageSize, String name) {
        log.info("name:{}",name);
        List<Course> courseIPage = courseMapper.selectPage(pageNum, pageSize, name);
        List<CourseRo> courseRoList = courseIPage.stream()
                .map(course -> CourseRo.builder()
                        .id(Long.valueOf(course.getId()))
                        .name(course.getName())
                        .courseUrl(course.getCourseUrl())
                        .coverUrl(course.getCoverUrl())
                        .count(course.getCount())
                        .build())
                .collect(Collectors.toList());
        redisService.setCacheObject(CacheConstants.COURSE_CACHE_KEY, courseRoList, TimeEnum.FOUR_HOUR);
        return courseRoList;
    }

    @Override
    public Course getById(Long id) {
        // 先查缓存
        String cacheKey = CacheConstants.COURSE_CACHE_KEY + id;
        Course course = redisService.getCacheObject(cacheKey, Course.class);
        if (course == null) {
            // 缓存中没有，查数据库
            course = courseMapper.selectById(Math.toIntExact(id));
            if (course != null) {
                // 写入缓存
                redisService.setCacheObject(cacheKey, course, TimeEnum.FOUR_HOUR);
            }
        }
        return course;
    }

    public boolean save(Course course) {
        int rows = courseMapper.insert(course);
        if (rows > 0) {
            String cacheKey = CacheConstants.COURSE_CACHE_KEY + course.getId();
            redisService.deleteObject(cacheKey);
        }
        return rows > 0;
    }
    @Override
    public boolean saveWithCourseUrl(Course course) {
        // 第一步：保存课程，此时数据库会自动生成 id
        boolean saved = this.save(course);
        if (!saved) {
            return false;
        }

        // 第二步：构造 courseUrl
        String courseUrl = "/course/" + course.getId();

        // 第三步：更新 course_url 字段
        int rows = courseMapper.updateCourseUrlById(course.getId(), courseUrl);

        if (rows > 0) {
            // 更新缓存
            String cacheKey = CacheConstants.COURSE_CACHE_KEY + course.getId();
            redisService.deleteObject(cacheKey); // 下次访问时重新加载
        }

        return rows > 0;
    }

    @Override
    public boolean exists(Long id) {
        return courseMapper.selectById(Math.toIntExact(id)) != null;
    }

    @Override
    public boolean updateById(Course course) {
        int rows = courseMapper.updateById(course);
        if (rows > 0) {
            // 更新后删除缓存，下次访问自动刷新
            String cacheKey = CacheConstants.COURSE_CACHE_KEY + course.getId();
            redisService.deleteObject(cacheKey);
        }
        return rows > 0;
    }

    @Override
    public boolean removeById(Long id) {
        int rows = courseMapper.deleteById(Math.toIntExact(id));
        if (rows > 0) {
            // 删除后清理缓存
            String cacheKey = CacheConstants.COURSE_CACHE_KEY + id;
            redisService.deleteObject(cacheKey);
        }
        return rows > 0;
    }

    @Override
    public Long getCourseCount() {
        String countKey = CacheConstants.COURSE_CACHE_KEY + "count";
        Long total = redisService.getCacheObject(countKey, Long.class);
        if (total == null || total == 0) {
            // 如果缓存中没有，则从数据库获取并重新设置缓存
            total = courseMapper.getCount();
            if (total > 0) {
                redisService.setCacheObject(countKey, total, TimeEnum.FOUR_HOUR);
            }
        }
        return total;
    }
    
    @Override
    public Long getPage(Integer pageSize) {
        String countKey = CacheConstants.COURSE_CACHE_KEY + "count";
        Long total = redisService.getCacheObject(countKey, Long.class);
        if (total == null || total == 0) {
            // 如果缓存中没有，则从数据库获取并重新设置缓存
            total = courseMapper.getCount();
            if (total > 0) {
                redisService.setCacheObject(countKey, total, TimeEnum.FOUR_HOUR);
            }
        }
        return total;
    }

    @Override
    public boolean saveById(Course course) {
        int rows = courseMapper.insert(course);
        return rows > 0;
    }
}